<template>
  <div class="app">
    <!-- 主体内容 -->
    <div class="main-content">
      <h1>主页面内容</h1>
      <button @click="toggleDrawer">打开/关闭抽屉</button>
    </div>

    <!-- 右侧抽屉 -->
    <div
      v-if="isDrawerOpen"
      class="drawer"
      :style="{ width: drawerWidth + 'px' }"
    >
      <div class="drawer-content">
        <p>这是右侧抽屉的内容</p>
      </div>

      <!-- 拖拽条 -->
      <div
        class="resizer"
        @mousedown="startResizing"
      ></div>
    </div>

    <!-- 遮罩层（可选） -->
    <div
      v-if="isDrawerOpen"
      class="overlay"
      @click="toggleDrawer"
    ></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

const isDrawerOpen = ref(false)
const drawerWidth = ref(300)
const isResizing = ref(false)

function toggleDrawer() {
  isDrawerOpen.value = !isDrawerOpen.value
}

function startResizing(e) {
  isResizing.value = true
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', stopResizing)
  e.preventDefault()
}

function stopResizing() {
  isResizing.value = false
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', stopResizing)
}

function handleMouseMove(e) {
  if (!isResizing.value) return

  const newWidth = window.innerWidth - e.clientX
  if (newWidth >= 150 && newWidth <= 600) {
    drawerWidth.value = newWidth
  }
}

// 可选：点击 ESC 关闭抽屉
function handleKeyDown(e) {
  if (e.key === 'Escape') {
    isDrawerOpen.value = false
  }
}

onMounted(() => {
  document.addEventListener('keydown', handleKeyDown)
})

onBeforeUnmount(() => {
  document.removeEventListener('keydown', handleKeyDown)
})
</script>

<style scoped>
.app {
  position: relative;
  height: 100vh;
  overflow: hidden;
}

.main-content {
  padding: 20px;
}

.drawer {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  transition: width 0.2s ease;
  display: flex;
  flex-direction: column;
}

.drawer-content {
  padding: 20px;
  flex: 1;
  overflow-y: auto;
}

.resizer {
  position: absolute;
  left: -5px; /* 让拖拽条更易点击 */
  top: 0;
  bottom: 0;
  width: 10px;
  cursor: ew-resize;
  background-color: transparent;
  z-index: 1001;
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: transparent;
  z-index: 999;
}
</style>